package com.palm.hubo2o.ui;

import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.palm.hubo2o.BaseActivity;
import com.palm.hubo2o.R;
import com.palm.hubo2o.event.BetEvent;
import com.palm.hubo2o.event.CleanLotteryEvent;
import com.palm.hubo2o.event.IssueEvent;
import com.palm.hubo2o.model.Bet;
import com.palm.hubo2o.model.Issue;
import com.palm.hubo2o.ui.fragment.LotteryFragment;
import com.palm.hubo2o.util.EnumCode;
import com.palm.hubo2o.util.IssueCenter;
import com.palm.hubo2o.ui.fragment.PastPrizesDialogFragment;
import com.palm.palmutils.widget.EasyRecyclerView;

import java.util.Locale;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by dest1 on 2015/9/21.
 */
public abstract class LotteryActivity extends BaseActivity implements ViewPager.OnPageChangeListener
        , EasyRecyclerView.OnItemClickListener, SensorEventListener {
    @Bind(R.id.tab)
    TabLayout tab;
    @Bind(R.id.vp)
    ViewPager vp;
    @Bind(R.id.txt_lottery_info)
    TextView info;


    private PastPrizesDialogFragment mPrizesDialog;

    private SensorManager sensorManager;
    private Vibrator vibrator;
    private LotteryFragment[] fragments;
    private IssueCenter mIssueCenter;
    private Bet mBet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lottery);
        vp.addOnPageChangeListener(this);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
        mIssueCenter = IssueCenter.open();
        if (mIssueCenter.switchIssue(gameId()) == null)
            mIssueCenter.startLoadCurrent(gameId());
        updateSubTitle();
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sensorManager != null)
            sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sensorManager != null)
            sensorManager.unregisterListener(this);
    }

    protected void addViewToDrawer(View v) {
//        if (v != null && v.getParent() == null)
//            mDrawer.addView(v);
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_lottery, menu);
//        return true;
//    }


    /**
     * 接收当前期变更消息
     */
    public void onEventMainThread(IssueEvent event) {
        if (gameId() == event.gameId)
            updateSubTitle();
    }

    private void updateSubTitle() {
        Issue i = mIssueCenter.switchIssue(gameId());
        if (i == null || i.issueNo < 0) {
            if (getSupportActionBar() != null) getSupportActionBar().setSubtitle("正在加载新期");
        } else {
            if (getSupportActionBar() != null)
                getSupportActionBar().setSubtitle(String.format(Locale.getDefault(), "第%d期", i.issueNo));
        }
    }


    /**
     * 生成的订单信息
     */
    public void onEvent(BetEvent event) {
        mBet = event.getBet();
        updateBetInfo();
    }

    @OnClick(R.id.btn_lottery_submit)
    public void actionSubmit() {
        if (mBet != null) {
//            if (mBet.getWagerCount() * 2 > Constant.MAX_PER_TICKET) {
//                Toast.makeText(this, "单期总金额不能超过1万元", Toast.LENGTH_SHORT).show();
//                return;
//            }
            Intent i = new Intent(this, BetActivity.class);
            i.putExtra("gameId", gameId());
            i.putExtra(Bet.TAG, mBet);
            startActivity(i);
        } else {
            Toast.makeText(this, "至少选择一注号码", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.btn_lottery_clean)
    public void actionClear() {
        EventBus.getDefault().post(new CleanLotteryEvent());
        mBet = null;
        updateBetInfo();
    }

    public void showPrizeDialog() {
        if (mPrizesDialog == null)
            mPrizesDialog = PastPrizesDialogFragment.getInstance(gameId());
        mPrizesDialog.show(getSupportFragmentManager(), PastPrizesDialogFragment.TAG);
    }

    private void updateBetInfo() {
        if (mBet != null) {
            info.setText(String.format(Locale.getDefault(), "共%d注，%d元", mBet.getWagerCount(), mBet.getWagerCount() * 2));
        } else {
            info.setText("共0注，0元");
        }
    }


    @NonNull
    protected abstract EnumCode.gameId gameId();

    protected void setFragments(LotteryFragment... fragments) {
        this.fragments = fragments;
        vp.setAdapter(lotteryAdapter);
        tab.setupWithViewPager(vp);
        if (tab.getTabCount() > 3)
            tab.setTabMode(TabLayout.MODE_SCROLLABLE);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        actionClear();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_trend) {
//            switch (gameId()) {
//                case HBP3:
//                    startActivity(new Intent(this, K3TrendActivity.class));
//                    break;
//                case C522:
//                    startActivity(new Intent(this, _225TrendActivity.class));
//                    break;
//                case QLC:
//                    startActivity(new Intent(this, QLCTrendActivity.class));
//                    break;
//                case SSQ:
//                    startActivity(new Intent(this, SSQTrendActivity.class));
//                    break;
//                case D3:
//                    startActivity(new Intent(this, D3TrendActivity.class));
//                    break;
//                default:
//                    break;
//            }
            return true;
        } else if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
//        mDragTopLayout.closeTopView(true);
        return true;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        //sensor状态改变
        if (true) {//设置是否需要摇一摇随机选号
            float x = event.values[0];//x轴加速度
            float y = event.values[1];//y轴加速度
            float z = event.values[2];//z轴加速度
            if (Math.sqrt(x * x + y * y) >= 12) {
                if (fragments[vp.getCurrentItem()].onRandomBalls())
                    vibrator.vibrate(200);
            }
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //sensor精度改变回调
    }

    private FragmentStatePagerAdapter lotteryAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {

        @Override
        public CharSequence getPageTitle(int position) {
            return fragments[position].getTitle();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments[position];
        }

        @Override
        public int getCount() {
            return fragments.length;
        }
    };


}
